package Chapter17.syn;

/**
 * @author 杨森
 * @date 2022年10月30日 21:08
 * 使用多线程，模拟三个窗口同时售票100张
 */
public class SellTicket {
    public static void main(String[] args) {
//        SellTicket01 sellTicket01 = new SellTicket01();
//        SellTicket01 sellTicket02 = new SellTicket01();
//        SellTicket01 sellTicket03 = new SellTicket01();
////        会出现超卖的现象
//        sellTicket01.start();
//        sellTicket02.start();
//        sellTicket03.start();

//还会出现超卖现象
//        SellTicket02 sellTicket02 = new SellTicket02();
//        new Thread(sellTicket02).start();
//        new Thread(sellTicket02).start();
//        new Thread(sellTicket02).start();

        SellTicket03 sellTicket03 = new SellTicket03();
        new Thread(sellTicket03).start();
        new Thread(sellTicket03).start();
        new Thread(sellTicket03).start();
    }
}

//实现接口方式，使用synchronized实现线程同步
class SellTicket03 implements Runnable {
    private int ticketnum = 100;//让多个线程共享ticketNum
    private boolean loop=true;
    public synchronized void sell(){//同步方法，在同一时刻，只能由一个线程来执行run方法
        if (ticketnum <= 0) {
            System.out.println("售票结束...");
            loop = false;
            return;
        }

        try {
            Thread.sleep(50);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("窗口" + Thread.currentThread()
                .getName() + "售出一张票" + "剩余票数="
                + (--ticketnum));

    }
    @Override
    public  void run() {
        while (loop) {
            sell();
        }
    }
}


//使用Thread方式
class SellTicket01 extends Thread {
    private static int ticketnum = 100;//让多个线程共享ticketNum

    @Override
    public void run() {
        while (true) {
            if (ticketnum <= 0) {
                System.out.println("售票结束...");
                break;
            }

            try {
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread()
                    .getName() + "售出一张票" + "剩余票数="
                    + (--ticketnum));
        }
    }
}

//使用接口方式
class SellTicket02 implements Runnable {
    private int ticketnum = 100;//让多个线程共享ticketNum

    @Override
    public void run() {
        while (true) {
            if (ticketnum <= 0) {
                System.out.println("售票结束...");
                break;
            }

            try {
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread()
                    .getName() + "售出一张票" + "剩余票数="
                    + (--ticketnum));
        }
    }
}

